package com.craftplay.controller;

import com.craftplay.VO.*;
import com.craftplay.common.PageBean;
import com.craftplay.common.ServerResponse;
import com.craftplay.dao.ClassOrderMapper;
import com.craftplay.dao.ClassTypeMapper;
import com.craftplay.dao.UnitMapper;
import com.craftplay.middleware.UnitPageService;
import com.craftplay.model.*;
import com.craftplay.service.*;
import com.craftplay.util.DateUtils;
import com.craftplay.util.ToolUntils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/play/moment")
public class MomentController {
    private static final Logger logger = LoggerFactory.getLogger(MomentController.class);

    @Autowired
    HostHolder hostHolder;

    @Autowired
    QiniuService qiniuService;

    @Autowired
    MomentService momentService;

    @Autowired
    UserService userService;

    @Autowired
    UnitPageService unitPageService;

    @Autowired
    CommentService commentService;

    @Autowired
    LoveService loveService;

    @Autowired
    FocusService focusService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private BehaveService behaveService;

    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private ClassTypeMapper classTypeMapper;

    @Autowired
    private ClassOrderMapper classOrderMapper;

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private WxMpService wxMpService;


    @RequestMapping(method = RequestMethod.POST, value = "/learn")
    @ResponseBody
    public ServerResponse<Unit> learn(@RequestBody Unit unit) {
        if (unit != null && hostHolder.getUser() != null) {
            unit.setUserId(hostHolder.getUser().getUserId());
            unit.setCreatedTime(new Date());
            unit.setUpdateTime(new Date());

            if (unit.getKind() == null) {
                return ServerResponse.createByErrorMessage("类型未选择！");
            }
            if (11 == unit.getKind() && unit.getParentId() == 0) {
                return ServerResponse.createByErrorMessage("回答没有父类！");
            }
            //课程发布
            if (12 == unit.getKind()) {
                User thisUser = hostHolder.getUser();
                if (thisUser.getUserType() == null || thisUser.getUserType() != 1) {
                    return ServerResponse.createByErrorMessage("不具备发布课程权限");
                }

                if (unit.getClassType() == null) {
                    return ServerResponse.createByErrorMessage("课程类型未选择");
                }

                if (unit.getClassTreeType() == null || unit.getClassTreeType() == "") {
                    return ServerResponse.createByErrorMessage("教学方式不能为空");
                }

                //计算价格
                String[] split = unit.getClassTreeType().split(",");
                String money = "";
                for (String classTreeType : split) {
                    ClassType classType = classTypeMapper.selectByMoney(unit.getClassType(), NumberUtils.toInt(classTreeType));
                    if (classType == null) {
                        return ServerResponse.createByErrorMessage("教学方式错误");
                    }
                    if (money == "") {
                        money = String.valueOf(classType.getClassTreeMoney());
                    } else {
                        money = money + "," + String.valueOf(classType.getClassTreeMoney());
                    }
                }
                unit.setClassMoney(money);
            }


            if (momentService.addMoment(unit) > 0) {
                if (8 == unit.getKind()) {
                    Unit parent = unitMapper.selectByPrimaryKey(unit.getParentId());
                    if (parent == null) {
                        return ServerResponse.createByErrorMessage("回答ID未找到");
                    }
                    unit.setScope(parent.getScope());
                    BehaveModel behaveModel = new BehaveModel();
                    behaveModel.setUserId(parent.getUserId());
                    behaveModel.setBuserId(unit.getUserId());
                    behaveModel.setUnitId(unit.getParentId());
                    behaveModel.setBehave("回答");
                    behaveModel.setCreateTime(new Date());
                    behaveService.insertBehave(behaveModel);


                    //推送模板消息
                    User user = userService.selectUserById(unit.getUserId());
                    User askUserId = userService.selectUserById(unit.getAskUserId());
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            .toUser(askUserId.getOpenId())
                            .templateId("v4WJCHWN24z0lMUl2eKbZQiUuzzVYr0vF-c-Pc3qIYU")
                            .url("http://playpro.live/#/tech/qj_activity_detail?id=" + unit.getId())
                            .build();

                    templateMessage.addData(new WxMpTemplateData("first", "亲爱的匠友，您的请教刚刚有人回覆喔～", "RED"));
                    templateMessage.addData(new WxMpTemplateData("keyword1", DateUtils.getNOW(), "RED"));
                    templateMessage.addData(new WxMpTemplateData("keyword2", unit.getTitle(), "RED"));
                    templateMessage.addData(new WxMpTemplateData("remark", "点击这里去看看吧 ！", "RED"));

                    try {
                        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                        System.out.println("发送模板消息失败");
                    }


                }
                if (9 == unit.getKind() && unit.getAskUserId() != null) {
                    BehaveModel behaveModel = new BehaveModel();
                    behaveModel.setUserId(unit.getUserId());
                    behaveModel.setBuserId(unit.getAskUserId());
                    behaveModel.setUnitId(unit.getParentId());
                    behaveModel.setBehave("请教");
                    behaveModel.setCreateTime(new Date());
                    behaveService.insertBehave(behaveModel);

                    //推送模板消息
                    User user = userService.selectUserById(unit.getUserId());
                    User askUserId = userService.selectUserById(unit.getAskUserId());
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            .toUser(askUserId.getOpenId())
                            .templateId("1Pp25MiA9SPv8rG5_w-0pL9sEnl-oZSW9VvLqA5W_9w")
                            .url("http://playpro.live/#/tech/qj_activity_detail?id=" + unit.getId())
                            .build();

                    templateMessage.addData(new WxMpTemplateData("first", "一位匠友刚向你提出了请教，诚盼你的指点喔～", "RED"));
                    templateMessage.addData(new WxMpTemplateData("keyword1", user.getNickname(), "RED"));
                    templateMessage.addData(new WxMpTemplateData("keyword2", unit.getTitle(), "RED"));
                    templateMessage.addData(new WxMpTemplateData("keyword3", DateUtils.getNOW(), "RED"));
                    templateMessage.addData(new WxMpTemplateData("remark", "点击这里去看看吧 ！", "RED"));

                    try {
                        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                        System.out.println("发送模板消息失败");
                    }
                }
                return ServerResponse.createBySuccess(unit);
            } else {
                return ServerResponse.createByErrorMessage("添加失败！");
            }
        }
        return ServerResponse.createByErrorMessage("添加失败！");
    }

    /**
     * 获取活动详情
     *
     * @param unitId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/unitdetail")
    @ResponseBody
    public ServerResponse<Unit> unitDetail(@RequestParam("id") int unitId) {
        Unit unit = momentService.oneMomentDetail(unitId);
        if (unit != null) {
            User user = userService.selectUserById(unit.getUserId());
            unit.setHeadImgUrl(user.getHeadUrl());
            unit.setUserName(user.getNickname());
            unit.setSex(user.getSex());
            return ServerResponse.createBySuccess(unit);
        }
        return ServerResponse.createByErrorMessage("查找失败！");
    }


    @RequestMapping(method = RequestMethod.POST, value = "/upunit")
    @ResponseBody
    public ServerResponse<String> updateUnit(@RequestBody Unit unit) {
        if (unit != null) {
            unit.setUpdateTime(new Date());
            if (momentService.updateMoment(unit) > 0) {
                return ServerResponse.createBySuccessMessage("添加成功");
            } else {
                return ServerResponse.createByErrorMessage("添加失败！");
            }
        }
        return ServerResponse.createByErrorMessage("添加失败！");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/oneunit")
    @ResponseBody
    public ServerResponse<List<Unit>> findByUser(@RequestParam("userId") Integer userId) {
        if (hostHolder.getUser() != null) {
            List<Unit> momentList = momentService.findMomentByUser(userId);
            for (Unit unit : momentList) {
                User user = userService.selectUserById(unit.getUserId());
                unit.setHeadImgUrl(user.getHeadUrl());
                unit.setUserName(user.getNickname());
                unit.setSex(user.getSex());
            }
            if (momentList != null) {
                return ServerResponse.createBySuccess(momentList);
            } else {
                return ServerResponse.createByErrorMessage("查找失败！");
            }
        }
        return ServerResponse.createByErrorMessage("查找失败！");
    }


    @RequestMapping(path = {"/uploadImage"}, method = {RequestMethod.POST})
    @ResponseBody
    public ServerResponse<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = qiniuService.saveImage(file);
            if (fileUrl == null) {
                return ServerResponse.createByErrorMessage("图片上传失败");
            }
            return ServerResponse.createBySuccess(fileUrl);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/searchunit")
    @ResponseBody
    public ServerResponse<UnitVOPageInfo> findUnitByCon(@RequestBody Condition condition) {
        ToolUntils.testReflect(condition);

        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        int flag = condition.getFlag();
        String address = condition.getAddress();
        int kind = condition.getKind();
        String scope = condition.getScope();
        int price = condition.getPrice();
        int dist = condition.getDist();
        double latitude = condition.getLatitude();
        double longitude = condition.getLongitude();
        int ret = condition.getRet();

        UnitVOPageInfo unitVOPageInfo = new UnitVOPageInfo();
        if (scope != null) {
            scope = scope.replaceAll("/", "|");
        }
        PageBean<Unit> pageBean = unitPageService.selectUnitListByCondition(flag, pageNum, pageSize, address, kind, scope, price, dist, ret, latitude, longitude);
        List<Unit> momentList = pageBean.getList();

        User thisUser = hostHolder.getUser();
        List<UnitVO> unitVOList = new ArrayList<UnitVO>();
        for (Unit unit : momentList) {
            UnitVO unitVO = new UnitVO();
            User user = userService.selectUserById(unit.getUserId());
            unit.setHeadImgUrl(user.getHeadUrl());
            unit.setUserName(user.getNickname());
            unit.setSex(user.getSex());
            unitVO.setUnit(unit);
            int unitId = unit.getId();
            List<CommentVO> commentVOList = commentService.getCommentList(unitId, thisUser.getUserId());
            unitVO.setCommentVOList(commentVOList);
            unitVOList.add(unitVO);
        }

        unitVOPageInfo.setUnitVOList(unitVOList);
        unitVOPageInfo.setPageSize(pageBean.getPages());
        if (unitVOList != null) {
            return ServerResponse.createBySuccess(unitVOPageInfo);
        } else {
            return ServerResponse.createByErrorMessage("查找失败！");
        }
    }


    /**
     * 获取活动详情
     *
     * @param unitId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getUnitDetail")
    @ResponseBody
    public ServerResponse<SkillsGive> getUnitDetail(@RequestParam("id") int unitId) {
        Unit unit = momentService.oneMomentDetail(unitId);
        User thisUser = hostHolder.getUser();
        if (unit != null || thisUser == null) {
            //获取kind的类型
            if (unit.getKind() == 8 && unit.getParentId() != -1) {
                unit = momentService.oneMomentDetail(unit.getParentId());
            }
            SkillsGive result = returnTotalJudge(unit, thisUser.getUserId(), true);

            List<SkillsGive> dircetion = new ArrayList<>();
            //所有指点
            if (unit.getKind() != 12) {
                List<Unit> unitDirectionsList = momentService.getUnitDirectionsList(unit.getId());
                for (int i = 0; i < unitDirectionsList.size(); i++) {
                    Unit dir = unitDirectionsList.get(i);
                    SkillsGive skillsGive = returnTotalJudge(dir, thisUser.getUserId(), true);
                    skillsGive.setCommentVOList(commentService.getUnitDetailComment(dir.getId(), dir.getUserId()));
                    if (skillsGive.getId().equals(unit.getId())) {
                        dircetion.add(0, skillsGive);
                    } else {
                        dircetion.add(skillsGive);
                    }
                }
            } else {
                result.setClassOrderId(unit.getId());
                if (unit.getUserId().equals(thisUser.getUserId())) {
                    result.setClassStatus(-1);
                } else {
                    //获取课程状态
                    ClassOrder classOrder = classOrderMapper.classStatus(thisUser.getUserId(), unit.getId());
                    if (classOrder != null && classOrder.getClassStatus() < 6) {
                        result.setClassOrderId(classOrder.getId());
                        result.setClassStatus(classOrder.getClassStatus());
                        if (classOrder.getClassStatus() == -2) {
                            //退款只为未购买状态
                            result.setClassOrderId(unit.getId());
                            result.setClassStatus(-3);
                        }
                    } else {
                        //未购买
                        result.setClassStatus(-3);
                    }
                }

                //获取指点
                unit.setKind(8);
                unit.setAnonymous(-1);
                unit.setScope(null);
                unit.setAddress(null);
                List<Unit> unitDirectionsList = momentService.getUnitByUserId(unit);
                for (int i = 0; i < unitDirectionsList.size(); i++) {
                    Unit dir = unitDirectionsList.get(i);
                    SkillsGive skillsGive = returnTotalJudge(dir, thisUser.getUserId(), true);
                    skillsGive.setCommentVOList(commentService.getUnitDetailComment(dir.getId(), dir.getUserId()));
                    if (skillsGive.getId() == unit.getId()) {
                        dircetion.add(0, skillsGive);
                    } else {
                        dircetion.add(skillsGive);
                    }
                    if (i > 5) {
                        break;
                    }
                }
            }

            result.setDirectionsList(dircetion);
            return ServerResponse.createBySuccess(result);
        }
        return ServerResponse.createByErrorMessage("查找失败！");
    }


    /**
     * 技能指点，技能请教，动态关注 首页接口
     *
     * @return
     */
    @PostMapping(value = "/getSkillsGive")
    @ResponseBody
    public ServerResponse<UnitGetVOPageInfo> getSkillsGive(@RequestBody Condition condition) {
        if (condition.getKind() == 0) {
            return ServerResponse.createByErrorMessage("参数错误！");
        }
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        UnitGetVOPageInfo pageInfo = new UnitGetVOPageInfo();
        List<SkillsGive> skillsGiveList = new ArrayList<>();
        User thisUser = hostHolder.getUser();
        PageBean<Unit> pageBean = null;
        String scope = condition.getScope();
        String address = condition.getAddress();
        // 10  动态关注
        if (condition.getKind() == 10) {
            List<Integer> userId = focusService.myFocusUser(thisUser.getUserId()).stream().map(Focus::getFocusUserId).collect(Collectors.toList());
            pageBean = momentService.findAllByFocusUserId(pageNum, pageSize, userId, scope, address);
            if (pageBean.getList() != null) {
                pageBean.getList().forEach(t -> {
                    SkillsGive result = returnTotalJudge(t, thisUser.getUserId(), true);
                    if (result.getKind() == 8) {
                        //指定获取请教
                        Unit consultUnit = momentService.oneMomentDetail(t.getParentId());
                        if (consultUnit != null) {
                            result.setConsult(returnTotalJudge(consultUnit, thisUser.getUserId(), false));
                        }
                    }
                    // 9  技能请教
                    if (result.getKind() == 9) {
                        //所有指点
                        List<Unit> unitDirectionsList = momentService.getUnitDirectionsList(t.getId());
                        List<SkillsGive> dirList = new ArrayList<>();
                        for (int i = 0; i < unitDirectionsList.size(); i++) {
                            if (i > 5) break;
                            dirList.add(returnTotalJudge(unitDirectionsList.get(i), thisUser.getUserId(), false));
                        }
                        result.setDirectionsList(dirList);
                    }
                    skillsGiveList.add(result);
                });
            }
        } else if (condition.getKind() == 99) {
            //99 推荐
            List<Integer> userId = userService.findTeacher(thisUser.getUserId()).stream().map(User::getUserId).collect(Collectors.toList());
            pageBean = momentService.findAllByFocusUserId(pageNum, pageSize, userId, scope, address);
            if (pageBean.getList() != null) {
                pageBean.getList().forEach(t -> {
                    SkillsGive result = returnTotalJudge(t, thisUser.getUserId(), true);
                    if (result.getKind() == 8) {
                        //指定获取请教
                        Unit consultUnit = momentService.oneMomentDetail(t.getParentId());
                        if (consultUnit != null) {
                            result.setConsult(returnTotalJudge(consultUnit, thisUser.getUserId(), false));
                        }
                    }
                    // 9  技能请教
                    if (result.getKind() == 9) {
                        //所有指点
                        List<Unit> unitDirectionsList = momentService.getUnitDirectionsList(t.getId());
                        List<SkillsGive> dirList = new ArrayList<>();
                        for (int i = 0; i < unitDirectionsList.size(); i++) {
                            if (i > 5) break;
                            dirList.add(returnTotalJudge(unitDirectionsList.get(i), thisUser.getUserId(), false));
                        }
                        result.setDirectionsList(dirList);
                    }
                    skillsGiveList.add(result);
                });
            }
        } else {
            //8 技能指点
            pageBean = momentService.findAllByKind(pageNum, pageSize, condition.getKind(), scope, address);
            if (condition.getKind() == 8) {
                pageBean.getList().forEach(unit -> {
                    SkillsGive skillsGive = returnTotalJudge(unit, thisUser.getUserId(), false);
                    skillsGiveList.add(skillsGive);
                });
            }

            // 9  技能请教
            if (condition.getKind() == 9) {
                pageBean.getList().forEach(unit -> {
                    SkillsGive skillsGive = returnTotalJudge(unit, thisUser.getUserId(), false);
                    //所有指点
                    List<Unit> unitDirectionsList = momentService.getUnitDirectionsList(unit.getId());
                    List<SkillsGive> dirList = new ArrayList<>();
                    for (int i = 0; i < unitDirectionsList.size(); i++) {
                        if (i > 5) break;
                        dirList.add(returnTotalJudge(unitDirectionsList.get(i), thisUser.getUserId(), false));
                    }
                    skillsGive.setDirectionsList(dirList);
                    skillsGiveList.add(skillsGive);
                });
            }
        }


        pageInfo.setPageSize(pageBean.getSize());
        pageInfo.setPageNum(pageBean.getPageNum());
        pageInfo.setPages(pageBean.getPages());
        pageInfo.setSkillsGives(skillsGiveList);

        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 附近课程
     *
     * @return
     */
    @PostMapping(value = "/getClassGive")
    @ResponseBody

    public ServerResponse<PageBean<UnitClassVO>> getClassGive(@RequestBody Condition condition) {
        condition.setKind(12);//默认课程
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        List<UnitClassVO> pageInfo = new ArrayList<>();
        PageBean<UnitClassVO> unitClassVOPageBean = new PageBean<>(pageInfo);
        User thisUser = hostHolder.getUser();
        String scope = condition.getScope();
        String address = condition.getAddress();

        //获取发布课程用户
        PageHelper.startPage(pageNum, pageSize);
        if (scope != null) {
            scope = scope.replaceAll("/", "|");
        }
        PageBean<Unit> allByClassGroupByUserId = momentService.findAllByClassGroupByUserId(scope, address);
        for (Unit dto : allByClassGroupByUserId.getList()) {
            UnitClassVO vo = new UnitClassVO();
            List<SkillsGive> volist = new ArrayList<>();
            List<Unit> classByUserId = momentService.findClassByUserId(dto.getUserId(), dto.getScope(), address, 2);
            for (int i = 0; i < classByUserId.size(); i++) {
                Unit unit = classByUserId.get(i);
                SkillsGive skillsGive = returnTotalJudge(classByUserId.get(i), thisUser.getUserId(), false);
                if (i == classByUserId.size() - 1) {
                    //所有指点
                    unit.setKind(8);
                    unit.setScope(null);
                    unit.setAddress(null);
                    unit.setAnonymous(-1);
                    List<Unit> unitDirectionsList = momentService.getUnitByUserId(unit);
                    List<SkillsGive> dirList = new ArrayList<>();
                    for (int j = 0; j < unitDirectionsList.size(); j++) {
                        if (j > 5) break;
                        dirList.add(returnTotalJudge(unitDirectionsList.get(j), thisUser.getUserId(), false));
                    }
                    skillsGive.setDirectionsList(dirList);
                }
                volist.add(skillsGive);
            }
            vo.setSkillsGives(volist);
            pageInfo.add(vo);
        }
        unitClassVOPageBean.setList(pageInfo);
        unitClassVOPageBean.setPageNum(pageNum);
        unitClassVOPageBean.setPageSize(pageSize);
        unitClassVOPageBean.setTotal(allByClassGroupByUserId.getTotal());
        return ServerResponse.createBySuccess(unitClassVOPageBean);
    }


    /**
     * 我的动态
     *
     * @return
     */
    @PostMapping(value = "/mySkillsGive")
    @ResponseBody
    public ServerResponse<UnitGetVOPageInfo> mySkillsGive(@RequestBody Condition condition) {

        if (condition.getUserId() == null) {
            return ServerResponse.createByErrorMessage("参数错误！userId未传");
        }
        Integer userId = condition.getUserId();
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        UnitGetVOPageInfo pageInfo = new UnitGetVOPageInfo();
        List<SkillsGive> skillsGiveList = new ArrayList<>();

        PageBean<Unit> pageBean;
        String scope = condition.getScope();
        String address = condition.getAddress();
        List<Integer> kindList = new ArrayList<>();
        kindList.add(8);
        kindList.add(9);
        kindList.add(10);
        kindList.add(11);
        User thisUser = hostHolder.getUser();
        Boolean anonymous = true;
        if (thisUser.getUserId().equals(condition.getUserId())) {
            anonymous = null;
        }
        pageBean = momentService.findAllByMyKind(pageNum, pageSize, kindList, userId, scope, address, anonymous);
        pageBean.getList().forEach(t -> {
            SkillsGive result = returnTotalJudge(t, userId, true);
            if (result.getKind() == 8) {
                //指定获取请教
                Unit consultUnit = momentService.oneMomentDetail(t.getParentId());
                if (consultUnit != null) {
                    result.setConsult(returnTotalJudge(consultUnit, userId, false));
                }
            }

            // 9  技能请教
            if (result.getKind() == 9) {
                //所有指点
                List<Unit> unitDirectionsList = momentService.getUnitDirectionsList(result.getId());
                List<SkillsGive> dirList = new ArrayList<>();
                for (int i = 0; i < unitDirectionsList.size(); i++) {
                    if (i > 5) break;
                    dirList.add(returnTotalJudge(unitDirectionsList.get(i), thisUser.getUserId(), false));
                }
                result.setDirectionsList(dirList);
            }
            skillsGiveList.add(result);
        });

        pageInfo.setPageSize(pageBean.getSize());
        pageInfo.setPageNum(pageBean.getPageNum());
        pageInfo.setPages(pageBean.getPages());
        pageInfo.setSkillsGives(skillsGiveList);

        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 返回的SkillsGive统一处理字段
     *
     * @param unit
     * @param userId
     * @return
     */
    private SkillsGive returnTotalJudge(Unit unit, int userId, boolean flag) {

        SkillsGive skillsGive = new SkillsGive();
        BeanUtils.copyProperties(unit, skillsGive);
        skillsGive.setLoveNum(loveService.numberLove(unit.getId()));
        skillsGive.setLove(loveService.isLove(unit.getId(), userId));
        skillsGive.setFocus(focusService.isFocusUser(userId, unit.getUserId()));
        skillsGive.setCollection(collectionService.isCollection(userId, unit.getId()));
        skillsGive.setCollectionNum(collectionService.collectionNum(unit.getId()));
        skillsGive.setFocusNum(focusService.focusMyUserNum(unit.getUserId()));

        //分类的标题
        if (unit.getParentId() != -1 && unit.getParentId() != 0) {
            Unit parentUnit = momentService.oneMomentDetail(unit.getParentId());
            if (parentUnit != null) {
                skillsGive.setParentTitle(parentUnit.getTitle());
                User parentUser = userService.selectUserById(parentUnit.getUserId());
                if (parentUnit.getAnonymous() == 0) {
                    skillsGive.setParentHeadImgUrl(parentUser.getHeadUrl());
                    skillsGive.setParentNickname(parentUser.getNickname());
                    skillsGive.setParentUserId(parentUnit.getUserId());
                } else if (parentUser != null) {
                    skillsGive.setParentHeadImgUrl("http://img.playpro.live/20190709223755.png");
                    skillsGive.setParentNickname("匿名匠友");
                    skillsGive.setParentUserId(-1);
                }
            }
        }

        //是否有请教别人
        if (unit.getAskUserId() != null) {
            User user = userService.selectUserById(unit.getAskUserId());
            skillsGive.setAskUserHeadImgUrl(user.getHeadUrl());
            skillsGive.setAskUserName(user.getNickname());
        }


        //是否付费可看
        if (unit.getPaySee() == 1) {
            //查询是否已经付费
            Boolean pay = orderService.isPay(userId, unit.getId());
            skillsGive.setPay(pay);
        }
        //匿名用户
        if (unit.getAnonymous() == 0) {
            User user = userService.selectUserById(unit.getUserId());
            skillsGive.setHeadImgUrl(user.getHeadUrl());
            skillsGive.setUserName(user.getNickname());
            skillsGive.setFeature(user.getFeature());
        } else {
            skillsGive.setUserId(-1);
            skillsGive.setHeadImgUrl("http://img.playpro.live/20190709223755.png");
            skillsGive.setUserName("匿名匠友");
        }
        if (flag) {
            //评论
            List<CommentVO> unitDetailComment = commentService.getUnitDetailComment(unit.getId(), userId);
            skillsGive.setCommentVOList(unitDetailComment);

            //回复
            List<SkillsGive> unitReplyList = momentService.getUnitReplyList(unit.getId());
            skillsGive.setReplyList(unitReplyList);
        }
        return skillsGive;
    }


    /**
     * 获取收藏列表
     *
     * @return
     */
    @PostMapping(value = "/getCollection")
    @ResponseBody
    public ServerResponse<List<SkillsGive>> getCollection(@RequestBody Condition condition) {
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<SkillsGive> skillsGiveList = new ArrayList<>();
        User thisUser = hostHolder.getUser();

        List<Collection> myCollection = collectionService.getMyCollection(thisUser.getUserId());

        List<Integer> unitList = myCollection.stream().map(Collection::getUnitId).collect(Collectors.toList());
        if (unitList.size() > 0) {
            List<Unit> allByUnitList = momentService.findAllByUnitList(unitList);
            allByUnitList.forEach(t -> {
                //8 技能指点
                if (t.getKind() == 8) {
                    SkillsGive skillsGive = returnTotalJudge(t, thisUser.getUserId(), false);
                    //指定获取请教
                    Unit consultUnit = momentService.oneMomentDetail(t.getParentId());
                    if (consultUnit != null) {
                        skillsGive.setConsult(returnTotalJudge(consultUnit, thisUser.getUserId(), false));
                    }
                }
                // 9  技能请教
                if (t.getKind() == 9) {
                    SkillsGive skillsGive = returnTotalJudge(t, thisUser.getUserId(), false);
                    //所有指点
                    List<Unit> unitDirectionsList = momentService.getUnitByUserId(t);
                    List<SkillsGive> dirList = new ArrayList<>();
                    for (int i = 0; i < unitDirectionsList.size(); i++) {
                        if (i > 5) break;
                        dirList.add(returnTotalJudge(unitDirectionsList.get(i), thisUser.getUserId(), false));
                    }
                    skillsGive.setDirectionsList(dirList);
                    skillsGiveList.add(skillsGive);
                }
            });
        }
        return ServerResponse.createBySuccess(skillsGiveList);
    }

    /**
     * 获取未阅读的消息数量
     *
     * @return
     */
    @GetMapping(value = "/getUnReadCount")
    @ResponseBody
    public ServerResponse<Integer> getUnReadCount() {
        User thisUser = hostHolder.getUser();
        int unReadCount = momentService.getUnReadCount(thisUser.getUserId());
        return ServerResponse.createBySuccess(unReadCount);
    }

    /**
     * 获取我的消息
     *
     * @return
     */
    @PostMapping(value = "/getMyMessage")
    @ResponseBody
    public ServerResponse<PageBean<BehaveModel>> getMyMessage(@RequestBody Condition condition) {
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        User thisUser = hostHolder.getUser();
        PageBean<BehaveModel> myMessage = momentService.getMyMessage(pageNum, pageSize, thisUser.getUserId(), condition.getIsRead());
        return ServerResponse.createBySuccess(myMessage);
    }


    /**
     * 阅读量+1
     *
     * @return
     */
    @GetMapping(value = "/addViewNum")
    @ResponseBody
    public ServerResponse<String> addViewNum(Integer unitId) {
        momentService.addViewNum(unitId);
        return ServerResponse.createBySuccessMessage("更新成功");
    }

    /**
     * 获得课程选择
     *
     * @param classType
     * @return
     */
    @RequestMapping(value = "/getClassType")
    @ResponseBody
    public ServerResponse<List<ClassType>> getClassType(ClassType classType) {
        if (classType.getClassType() == null) {
            List<ClassType> classTypes = classTypeMapper.selectByClassType();
            return ServerResponse.createBySuccess(classTypes);
        } else {
            List<ClassType> classTypes = classTypeMapper.selectByClassTree(classType.getClassType());
            return ServerResponse.createBySuccess(classTypes);
        }
    }


    /**
     * 课程管理
     *
     * @return
     */
    @RequestMapping(value = "/classManage")
    @ResponseBody
    public PageBean<OrderDTO> classManage(@RequestBody Condition condition) {
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize);
        User thisUser = hostHolder.getUser();
        List<OrderDTO> orderDTOS = new ArrayList<>();
        PageBean<OrderDTO> outDTO = new PageBean<>(orderDTOS);
        List<ClassOrder> classOrders = classOrderMapper.selectByUserId(thisUser.getUserId());
        classOrders.stream().forEach(t -> {
            User user = userService.selectUserById(t.getUserId());
            OrderDTO dto = new OrderDTO();
            dto.setId(t.getId());
            dto.setUserName(user.getNickname());
            dto.setHeadUrl(user.getHeadUrl());
            dto.setUserId(user.getUserId());
            List<ClassType> classTypes = classTypeMapper.selectByClassTree(t.getClassType());
            for (ClassType classType : classTypes) {
                if (classType.getClassTreeType() == t.getClassTreeType()) {
                    dto.setClassTreeDesc(classType.getClassTreeDesc());
                    dto.setClassDesc(classType.getClassDesc());
                }
            }
            dto.setCreateTime(t.getCreateTime());
            dto.setMessage(t.getMessage());
            dto.setStatus(t.getClassStatus());
            dto.setMoney((double) t.getMoney() / 100);
            dto.setTel(user.getTel());
            orderDTOS.add(dto);
        });
        outDTO.setList(orderDTOS);
        outDTO.setPageNum(pageNum);
        outDTO.setPageSize(pageSize);
        outDTO.setTotal(objects.getTotal());
        return outDTO;
    }


    /**
     * 课程状态变更
     *
     * @return
     */
    @RequestMapping(value = "/changeClassStatus")
    @ResponseBody
    @Transactional
    public ServerResponse<SkillsGive> changeClassStatus(@RequestParam("id") int id) {
        User thisUser = hostHolder.getUser();
        ClassOrder classOrder = classOrderMapper.selectById(id);
        if (classOrder == null) {
            return ServerResponse.createByErrorMessage("课程获取失败");
        }
        if (classOrder.getClassStatus() == 0) {
            if (classOrder.getUserId() == thisUser.getUserId()) {
                return ServerResponse.createByErrorMessage("不能改变该订单");
            }
        }
        int i = classOrderMapper.changeClassStatus(id);

        if (i > 0) {
            classOrder.setClassStatus(classOrder.getClassStatus() + 1);
            if (classOrder.getClassStatus() == 1) {
                //支付定金
                weixinService.sendClassRedPacket(classOrder);
                //标记定金支付
                classOrder.setStatus(1);
            }
            classOrderMapper.updateStatus(classOrder);
            return ServerResponse.createBySuccessMessage("更新成功");
        }

        return ServerResponse.createByErrorMessage("更新错误");
    }


    /**
     * 我的发布课程
     *
     * @return
     */
    @PostMapping(value = "/myClass")
    @ResponseBody
    public ServerResponse<UnitGetVOPageInfo> myClass(@RequestBody Condition condition) {

        if (condition.getUserId() == null) {
            return ServerResponse.createByErrorMessage("参数错误！userId未传");
        }
        Integer userId = condition.getUserId();
        int pageNum = condition.getPageNum();
        int pageSize = condition.getPageSize();
        UnitGetVOPageInfo pageInfo = new UnitGetVOPageInfo();
        List<SkillsGive> skillsGiveList = new ArrayList<>();

        PageBean<Unit> pageBean;
        String scope = condition.getScope();
        String address = condition.getAddress();
        List<Integer> kindList = new ArrayList<>();
        kindList.add(12);
        User thisUser = hostHolder.getUser();
        Boolean anonymous = true;
        if (thisUser.getUserId().equals(condition.getUserId())) {
            anonymous = null;
        }
        pageBean = momentService.findAllByMyKind(pageNum, pageSize, kindList, userId, scope, address, anonymous);
        pageBean.getList().forEach(t -> {
            SkillsGive result = returnTotalJudge(t, userId, false);
            skillsGiveList.add(result);
        });

        pageInfo.setPageSize(pageBean.getSize());
        pageInfo.setPageNum(pageBean.getPageNum());
        pageInfo.setPages(pageBean.getPages());
        pageInfo.setSkillsGives(skillsGiveList);

        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 我的参与的课程，
     *
     * @return
     */
    @PostMapping(value = "/myJoinClass")
    @ResponseBody
    public ServerResponse<UnitGetVOPageInfo> myJoinClass(@RequestBody Condition condition) {

        if (condition.getUserId() == null) {
            return ServerResponse.createByErrorMessage("参数错误！userId未传");
        }
        Integer userId = condition.getUserId();
        UnitGetVOPageInfo pageInfo = new UnitGetVOPageInfo();
        List<SkillsGive> skillsGiveList = new ArrayList<>();

        List<Integer> kindList = new ArrayList<>();
        kindList.add(12);
        User thisUser = hostHolder.getUser();

        List<ClassOrder> classOrders = classOrderMapper.selectByJoinUserId(thisUser.getUserId());
        List<Integer> unitList = classOrders.stream().map(ClassOrder::getUnitId).collect(Collectors.toList());
        if (unitList != null && unitList.size() > 0) {
            List<Unit> allByUnitList = momentService.findAllByUnitList(unitList);
            allByUnitList.forEach(t -> {
                SkillsGive result = returnTotalJudge(t, userId, false);
                skillsGiveList.add(result);
            });
        }
        pageInfo.setSkillsGives(skillsGiveList);

        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 我的申请，
     *
     * @return
     */
    @PostMapping(value = "/myApplyClass")
    @ResponseBody
    public ServerResponse<UnitGetVOPageInfo> myApplyClass(@RequestBody Condition condition) {

        if (condition.getUserId() == null) {
            return ServerResponse.createByErrorMessage("参数错误！userId未传");
        }
        Integer userId = condition.getUserId();
        UnitGetVOPageInfo pageInfo = new UnitGetVOPageInfo();
        List<SkillsGive> skillsGiveList = new ArrayList<>();

        List<Integer> kindList = new ArrayList<>();
        kindList.add(12);
        User thisUser = hostHolder.getUser();

        List<ClassOrder> classOrders = classOrderMapper.selectByApplyUserId(thisUser.getUserId());
        List<Integer> unitList = classOrders.stream().map(ClassOrder::getUnitId).collect(Collectors.toList());
        if (unitList != null && unitList.size() > 0) {
            List<Unit> allByUnitList = momentService.findAllByUnitList(unitList);
            allByUnitList.forEach(t -> {
                SkillsGive result = returnTotalJudge(t, userId, false);
                skillsGiveList.add(result);
            });
        }
        pageInfo.setSkillsGives(skillsGiveList);

        return ServerResponse.createBySuccess(pageInfo);
    }


}
